
import time
import json
import sys
import traceback
import ssl

from functools import wraps

ssl._create_default_https_context = ssl._create_unverified_context

PY2 = sys.version_info[0] == 2
PY3 = sys.version_info[0] == 3

if PY3:
    import urllib.request
    import urllib.error
    from urllib.parse import urlencode, quote
    from urllib.request import urlopen
elif PY2:
    import urllib
    import urllib2
    from urllib2 import urlopen
    from urllib import urlencode


def show_time(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        # if not can_run:
        #     return "Function will not run"
        t1 = time.time()
        rv = f(*args, **kwargs)
        t2 = time.time()
        print('http use time:', t2 - t1)
        return rv

    return decorated


@show_time
def http_post_v2(req_url, args, **opt):
    show_header = opt.get('show_header', False)
    cookie = opt.get('cookie')
    get_cookie = opt.get('get_cookie')
    timeout = opt.get("timeout", 60)

    data = json.dumps(args, ensure_ascii=False)

    req_url = quote(req_url, safe=':/?=&')
    print("req_url quote:", req_url)
    if PY3:
        data = bytes(data, 'utf8')

    # print('data', data, type(data))
    # print('cookie:', type(context.get('cookie')))
    #
    header = {
        'Content-Type': 'application/json;charset=UTF-8',
    }
    if cookie:
        header["Cookie"] = cookie

    print("header:", header)

    #
    if PY3:
        req = urllib.request.Request(req_url, data, headers=header)
        # rsp = urllib2.urlopen(req,timeout=0.1)   # for test timeout arg
        rsp = urllib.request.urlopen(req, timeout=timeout)
    elif PY2:
        req = urllib2.Request(req_url, data, headers=header)
        # rsp = urllib2.urlopen(req,timeout=0.1)   # for test timeout arg
        rsp = urllib2.urlopen(req, timeout=timeout)

    rv = rsp.read()
    if show_header:
        print('header:', rsp.headers)

    set_cookie = rsp.headers.get('Set-Cookie')

    try:
        rsp_json = json.loads(rv)
    except Exception as e:
        print(traceback.format_exc())
        return rv

    if get_cookie:
        return rsp_json, set_cookie

    return rsp_json
